﻿@using System.Net.Http.Json
@using MudBlazor.Examples.Data.Models
@namespace MudBlazor.Docs.Examples
@inject HttpClient httpClient

<style>
    .selected {
        background-color: #1E88E5 !important;
    }
    .selected > td {
        color: white !important;
    }
    .selected > td .mud-input {
        color: white !important;
    }
</style>

<MudTable T="Element" Items="@Elements.Take(4)" Hover="true" Breakpoint="Breakpoint.Sm" @ref="mudTable"
          RowClass="cursor-pointer" RowClassFunc="@SelectedRowClassFunc" OnRowClick="RowClickEvent">
    <HeaderContent>
        <MudTh>Nr</MudTh>
        <MudTh>Sign</MudTh>
        <MudTh>Name</MudTh>
        <MudTh>Position</MudTh>
        <MudTh>Molar mass</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="Nr">@context.Number</MudTd>
        <MudTd DataLabel="Sign">@context.Sign</MudTd>
        <MudTd DataLabel="Name">@context.Name</MudTd>
        <MudTd DataLabel="Position">@context.Position</MudTd>
        <MudTd DataLabel="Molar mass">@context.Molar</MudTd>
    </RowTemplate>
</MudTable>
<MudExpansionPanels Style="flex: 1;">
    <MudExpansionPanel Text="Show inline-clicked event log">
        @foreach (var message in clickedEvents)
        {
            <MudText>@message</MudText>
        }
        @if(clickedEvents.Count > 0) {
            <div class="d-flex">
                <MudSpacer/>
                <MudButton Class="mt-3" ButtonType="ButtonType.Button" Variant="Variant.Filled" OnClick="@(() => clickedEvents.Clear())">Clear events</MudButton>
            </div>
        }
    </MudExpansionPanel>
</MudExpansionPanels>

@code {
    private int selectedRowNumber = -1;
    private MudTable<Element> mudTable;
    private List<string> clickedEvents = new();
    private IEnumerable<Element> Elements = new List<Element>()
    {
        new Element() { Number = 1, Sign = "H", Name = "Hydrogen", Position = 0, Molar = 1.00794 },
        new Element() { Number = 2, Sign = "He", Name = "Helium", Position = 17, Molar = 4.002602 },
        new Element() { Number = 3, Sign = "Li", Name = "Lithium", Position = 0, Molar = 6.941 }
    };

    private void RowClickEvent(TableRowClickEventArgs<Element> tableRowClickEventArgs)
    {
        clickedEvents.Add("Row has been clicked");
    }

    private string SelectedRowClassFunc(Element element, int rowNumber)
    {
        if (selectedRowNumber == rowNumber)
        {
            selectedRowNumber = -1;
            clickedEvents.Add("Selected Row: None");
            return string.Empty;
        }
        else if (mudTable.SelectedItem != null && mudTable.SelectedItem.Equals(element))
        {
            selectedRowNumber = rowNumber;
            clickedEvents.Add($"Selected Row: {rowNumber}");
            return "selected";
        }
        else
        {
            return string.Empty;
        }
    }
}
